DAY21:Highest Scoring Word


Posted by birdbirdmurmur on 2023-08-03

題目連結

Highest Scoring Word

解法

Javascript

function high(x){
  function calculateScore (word){
    const alphabet = "abcdefghijklmnopqrstuvwxyz"
    return word.split('').reduce( (score, letter) => score + alphabet.indexOf(letter) + 1 , 0)
  }

  const words = x.split(' ')
  let highestWord = ''
  let highestScore = 0

  words.forEach( (word) => {
    const score = calculateScore(word)
    if (score > highestScore || (score === highestScore && word < highestWord.length)){
        highestScore = score
        highestWord = word
        }
  })
    return highestWord
}

心得

先把x用split(' ')做拆解
預設兩個值:最高分數最高分單字
將拆解後的words進迴圈比大小
同時建立一個轉換分數的function
如果轉換後的分數大於highestScorehighestWord就替換掉
同分就比單字的長度
最後回傳(每次都忘記回傳 不然就是設立在迴圈裡頭)


#javascript #Codewars







Related Posts

Day 102

Day 102

[JS102] Jest

[JS102] Jest

[PD101] 淺談產品開發與工作流程

[PD101] 淺談產品開發與工作流程


Comments